
//
//  UIImage+Extension.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/18.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit
extension UIImage {
    //异步绘制图片
    func hd_AsyncDrawImage(var size: CGSize? , bgColor:UIColor? = UIColor.whiteColor(), isCorner:Bool = false , drawFinish:(image: UIImage)->()){
        //1.开启异步线性
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            //2.设置默认尺寸
            if  size == nil {
                size = self.size
            }
            //3.设置上下文的rect
            let rect  = CGRect(origin: CGPointZero, size: size!)
            
            //4.开启上下文
            UIGraphicsBeginImageContextWithOptions(size!, bgColor != nil , UIScreen.mainScreen().scale)
            
            //5.设置背景颜色
            bgColor?.setFill()
            UIRectFill(rect)
            
            //6.设置圆角
            if isCorner {
                //路径
                let  path = UIBezierPath(ovalInRect: rect)
                path.addClip()
            }
            
            //7.绘图
            self.drawInRect(rect)
            
            //8.获取新图片
            let  newImage = UIGraphicsGetImageFromCurrentImageContext()
            
            //9.结束上下文
              UIGraphicsEndImageContext()
            
            //10.将图片传出去
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                drawFinish(image: newImage)
            })
            
            
        }
        
    }
    

    
}